/**
 * 
 */
package com.youth.fund.hk.hostManager.manager.web.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.baidu.ueditor.ActionEnter;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.youth.fund.hk.hostManager.manager.service.UploadService;
import com.youth.fund.hk.hostManager.ueditor.ManagerActionEnter;

/**
 * @author Sunk_Sky
 *
 *         2014年12月21日下午9:10:22
 */
@Controller
@RequestMapping("/json/ueditor")
public class UeditorController
{
	@Autowired
	@Qualifier("UploadService")
	private UploadService testService;
	
	@Value("${ueditor.configPath}")
	private String configPath;
	
	@Value("${ueditor.HostIp}")
	private String ueditorHostIp;
	
	
	@RequestMapping(value = "/config.json")
	public @ResponseBody Object getConfig(HttpServletRequest request,
			HttpServletResponse response, Model model)
	{
		response.setHeader("Content-Type", "text/html");
		
		String action = request.getParameter("action");
		
		ServletContext servlet = request.getSession().getServletContext();

		String rootPath = servlet.getRealPath("/");
		
		if("uploadimage".equalsIgnoreCase(action))
		{
			DefaultMultipartHttpServletRequest mrequest = (DefaultMultipartHttpServletRequest)request;
			
			MultiValueMap<String, MultipartFile> fileMap = mrequest.getMultiFileMap();
			
			this.testService.uoloadUeditorImage(fileMap.getFirst("upfile"), rootPath);
			
			State result = new BaseState(true, 0);
			
			System.out.println(action);
			
			return result.toJSONString();
		}
		ManagerActionEnter ae = new ManagerActionEnter(request, rootPath,this.configPath);

		String ssss = request.getRequestURI();
		
		System.out.println(ssss);
		
		String temp = ae.exec();
		
		if("listimage".equalsIgnoreCase(action))
		{
			temp = temp.replace("WEB-INF/", "");
		}
		
		temp = temp.replace("${ueditorHostIp}", this.ueditorHostIp);

		return temp;
	}
}
